package cn.gailvlun.gll.presentation.xroom.adapter

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.cross.AnswerQuestionReq
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.dialog_input_answer.*


class InputAnswerDialog(context: Context, private val isFirst: Boolean, private val matchId: Int,
                        private val countDownTime: Int) : BaseDialog(context) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.dialog_input_answer)

        et_answer.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
                btn_ensure.isEnabled = s.isNotEmpty()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })

        btn_ensure.setOnClickListener {
            val req = AnswerQuestionReq()
            req.answer = et_answer.text.toString()
            req.x_match_result_id = matchId
            req.isIs_first = this.isFirst

            HttpMethods.getCrossService()
                    .answerQuestion(req)
                    .compose(RxUtil.applyScheduler())
                    .subscribe(object : HttpSubscriber<PlaceHolder>() {
                        override fun onSuccess(response: PlaceHolder?) {
                            secureDismiss()
                        }

                        override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
                            DialogUtil.showError(context, errMsg)
                        }
                    })
        }

        cdv.toggle()
        RxUtil.countDown(countDownTime.toLong())
                .subscribe(object: Observer<Long> {
                    override fun onComplete() {
                        secureDismiss()
                    }

                    override fun onSubscribe(d: Disposable) {
                        countDown = d
                    }

                    override fun onNext(t: Long) {
                        cdv.setText(t.toInt())
                    }

                    override fun onError(e: Throwable) {

                    }

                })

        setCancelable(false)
    }

    private var countDown: Disposable? = null

    override fun secureDismiss() {
        super.secureDismiss()

        countDown?.dispose()
    }
}